<template>
	<div class="heightMax order publicbox" v-loading='loadingCon'>
		<div class="listName">
			<div class="listNameBox"><i></i><span class="font14">角色信息</span></div>
			<div>
				<el-button type="primary" size="mini" @click="addRole('form')" v-if="!isDisabled" v-loading='submitLoading'>保存</el-button>
				<el-button size="mini" @click='backRouter'>返回</el-button>
			</div>
		</div>
		<vueScroll style='height: 90%;'>
			<el-form :model="form" :rules="rules" ref="form" :label-width="formLabelWidth" style='margin-top: 25px;height: 100%;'
			 size="mini">
				<el-row>
					<el-col :span="6" :offset='1'>
						<el-form-item label="角色名称:" prop="roleName">
							<el-input size="mini" placeholder="请输入角色名称" v-model.trim="form.roleName" autocomplete="off" clearable :disabled='isDisabled'></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6" :offset='1'>
						<el-form-item label="角色类型:" prop="roleGenre">
							<el-select size="mini" v-model="form.roleGenre" placeholder="请选择角色类型" clearable :disabled='isDisabled' @change="roleTypeChange">
								<el-option v-for="item in roleGenreArr" :value="item.value" :label="item.label" :key='item.value'>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6" :offset='1'>
						<el-form-item label="数据权限类型:" prop="dataAuthority">
							<el-select size="mini" v-model="form.dataAuthority" placeholder="请选择数据权限类型" @change="selectChange" clearable
							 :disabled='isDisabled'>
								<el-option v-for="item in dataAuthorityArr" :value="item.value" :label="item.label" :key='item.value'>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="6" :offset='1' v-if="form.roleGenre != 0">
						<el-form-item label="所属组织:" prop="branchValue">
							<el-cascader filterable :show-all-levels="false" v-model='form.branchValue' :options="newOptions" :props="{value:'id',children:'list',label:'name',checkStrictly: true,emitPath:false }"
							 size="mini" placeholder="请选择所属组织" clearable :disabled='isDisabled || isType'></el-cascader>
						</el-form-item>
					</el-col>
					<el-col :span="13" :offset='1'>
						<el-form-item label="角色备注:" prop="roleComment">
							<el-input placeholder="角色备注" size="mini" type="textarea" resize='none' :rows="4" v-model="form.roleComment"
							 autocomplete="off" clearable :disabled='isDisabled'></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row v-if="!dataPermission">
					<el-col :span="20" :offset='1'>
						<el-form-item label="已自选电梯:">
							<el-select size="mini" v-model="choseLiftList" clearable :disabled='isDisabled' multiple placeholder="请点击选授权电梯">
								<el-option v-for="(item,index) in choseLiftArr" :value="item" :label="item" :key='index'>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row v-if="isShowCheck">
					<el-col :span="6" :offset='1'>
						<el-form-item label="系统默认:">
							<el-checkbox v-model="isChecked" class="fl"></el-checkbox>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="treeBox">
				<div class="treeItem">
					<div class="listName">
						<div class="listNameBox"><i></i><span class="font14">功能权限</span></div>
					</div>
					<div class="allChose">
						<el-checkbox class='checkBox' v-model="checked" @change="checkedAll" /><span>全选</span>
					</div>
					<el-tree ref='treeLeft' :data="data" show-checkbox node-key="pid" :default-expand-all='true'
					 :default-expanded-keys="defaultExpandedKeysArr" :default-checked-keys="defaultCheckedKeysArr" :props="defaultProps"
					 @check='tree1Check' @check-change='checkChange'>
					</el-tree>
				</div>
				<div class="treeItem">
					<div class="listName">
						<div class="listNameBox"><i></i><span class="font14">数据权限</span></div>
					</div>
					<el-tree ref='treeRight' :data="treePermission" show-checkbox node-key="id" :default-expand-all='true'
					 :default-expanded-keys="defaultExpandedKeysArr1" :default-checked-keys="newDefaultCheckedKeysArr" :props="defaultProps1"
					 v-show="dataPermission" :check-strictly='true' @check='tree2Check'>
					</el-tree>
					<el-button type="primary" size="mini" class='fl' @click='choseLift' v-show='!dataPermission' :disabled='operationType == 2'>
						选择授权电梯
					</el-button>
				</div>
			</div>
		</vueScroll>
	</div>
</template>

<script>
	import {
		loadFn,
		axiosPost,
		axiosGet,
		axiosDelete,
		axiosPut,
		AllLoading,
		axiosChange
	} from "@/common.js";
	import {
		roleName,
		dataAuthority,
		roleComment,
		branchValue,
		roleGenre
	} from './rule.js'
	export default {
		props: {
			operationType: {
				type: Number,
				default () {
					return 0 //0是添加  1是编辑  2是详情
				}
			}
		},
		activated() {
			this.getPermission()
			this.changeUserTypeArr()
			if (localStorage.choseLiftData) {
				this.$store.state.choseLiftData = JSON.parse(localStorage.choseLiftData).data
				this.choseLiftList = this.$store.state.choseLiftData
			} else {
				if (this.operationType) {
					if (localStorage.roleOperation) {
						this.compileId = JSON.parse(localStorage.roleOperation).id
					} else {
						this.compileId = ''
					}
					if (this.role == 0) {
						this.roleGenreArr.push({
							value: 10,
							label: '维保人员'
						})
					}
					this.getCompileData()
				} else {
					this.defaultCheckedKeysArr = []
					this.newDefaultCheckedKeysArr = []
					this.$refs['form'].resetFields();
				}
			}
		},
		deactivated() {
			console.log('没了')
			localStorage.removeItem('choseLiftData')
		},
		data() {
			return {
				isChecked:false,
				checked: false,
				newOptions: [],
				selectedLoading: false,
				submitLoading: false,
				loadingCon: true,
				roleGenreArr: [],
				formLabelWidth: '120px',
				affiliatedArr: [],
				dataAuthorityArr: [{
						value: 10,
						label: '部门'
					},
					{
						value: 20,
						label: '自选'
					},
				],
				form: {
					roleName: '',
					affiliated: '',
					dataAuthority: 10,
					roleComment: '',
					branchValue: '',
					roleGenre: '',
				},
				rules: {
					roleName,
					dataAuthority,
					roleComment,
					branchValue,
					roleGenre
				},
				currentOrganizationId: '',
				dataPermission: true,
				//功能权限
				data: [],
				// 默认展开的节点的 key 的数组
				defaultExpandedKeysArr: [],
				// 默认勾选的节点的 key 的数组
				defaultCheckedKeysArr: [],
				defaultProps: {
					children: 'pids',
					label: 'name'
				},
				//数据权限
				treePermission: [],
				// 默认展开的节点的 key 的数组
				defaultExpandedKeysArr1: [],
				// 默认勾选的节点的 key 的数组
				newDefaultCheckedKeysArr: [],
				defaultProps1: {
					children: 'list',
					label: 'name'
				},
				choseLiftList: [],
				compileId: '',
			}
		},
		computed: {
			isShowCheck(){
				if(this.role == 0 && localStorage.username && JSON.parse(localStorage.username).name == 'admin'){
					return true
				}else{
					return false
				}
			},
			isType() {
				if (this.form.roleGenre !== '') {
					return false
				} else {
					return true
				}
			},
			role() {
				if (localStorage.role) {
					return JSON.parse(localStorage.role).id
				} else {
					return ''
				}
			},
			isDisabled() {
				if (this.operationType == 2) {
					return true
				} else {
					return false
				}
			},
			choseLiftArr() {
				return this.$store.state.choseLiftData
			},
		},
		methods: {
			checkChange(value1, value2) {

			},
			checkedAll(res) {
				if (res) {
					this.$refs.treeLeft.setCheckedNodes(this.data);
				} else {
					this.$refs.treeLeft.setCheckedNodes([]);
				}
			},
			getOrganization(res) {
				let params = {
					page: 1,
					page_size_count: 999,
					key_words: '',
					role_type: res
				}
				axiosGet('/user/role/organization/', params, (res) => {
					if (res.code == 0) {
						this.newOptions = res.detail.org
						console.log(this.newOptions)
					} else {
						this.$message.error(res.detail.result)
					}
				})
			},
			roleTypeChange(res) {
				if (res !== '') {
					if (res == 0) {
						this.form.branchValue = ''
					}
					this.getOrganization(res)
				} else {
					this.form.branchValue = ''
				}
			},
			//设置左侧tree默认值
			tree1Check(value1, value2) {
				this.defaultCheckedKeysArr = value2.checkedKeys
			},
			//设置右侧tree默认值
			tree2Check(value1, value2) {
				this.newDefaultCheckedKeysArr = value2.checkedKeys
			},
			//角色类型变化
			changeUserTypeArr() {
				if (this.role == 0) {
					this.roleGenreArr = [{
							label: '平台管理员',
							value: 0,
						},
						{
							label: '维保单位用户',
							value: 20,
						},
						{
							label: '使用单位用户',
							value: 30,
						},
						{
							label: '监管单位',
							value: 40,
						}
					]
				} else if (this.role == 20) {
					this.roleGenreArr = [{
							label: '维保人员',
							value: 10,
						},
						{
							label: '维保单位用户',
							value: 20,
						},
						{
							label: '使用单位用户',
							value: 30,
						}
					]
				} else if (this.role == 30) {
					this.roleGenreArr = [{
						label: '使用单位用户',
						value: 30,
					}]
				} else if (this.role == 40) {
					this.roleGenreArr = [{
						label: '监管单位',
						value: 40,
					}]
				}
			},
			//数据权限数据
			getJurisData(newValue) {
				this.treePermission = []
				let params = {
					organization: this.currentOrganizationId,
					flag: ''
				}
				axiosGet('/user/organization/organize/', params, (res) => {
					if (res.code == 0) {
						if (Object.keys(res.detail).length != 0) {
							let arr = []
							arr.push(res.detail)
							this.treePermission = arr
						}
						if (newValue) {
							this.newDefaultCheckedKeysArr = newValue
						}
					} else {
						this.$message.error(res.detail.result)
					}
				})
			},
			//返回父级路由
			backRouter() {
				let obj = {
					name: '角色管理',
					router: '/MainView/SystemManagement/RoleManagement'
				}
				this.$refs['form'].resetFields();
				this.$store.commit('GOTAGROUTER', obj)
			},
			//获取编辑数据
			getCompileData() {
				let url = '/user/role/' + this.compileId
				axiosGet(url, {}, (res) => {
					if (res.code == 0) {
						this.form.roleName = res.detail.role_name
						this.form.roleComment = res.detail.role_desc
						this.form.roleGenre = res.detail.role_type
						this.defaultCheckedKeysArr = res.detail.permissions
						this.form.branchValue = res.detail.management.id
						this.isChecked = !!res.detail.create_for_all
						this.$set(this.form, 'dataAuthority', res.detail.management_type)
						if (this.form.dataAuthority == 10) {
							this.dataPermission = true
						} else {
							this.dataPermission = false
						}
						if (localStorage.choseLiftData) {
							this.$store.state.choseLiftData = JSON.parse(localStorage.choseLiftData).data
							this.choseLiftList = this.$store.state.choseLiftData
						} else {
							this.$store.state.choseLiftData = res.detail.register_codes
							this.choseLiftList = res.detail.register_codes
						}
						this.currentOrganizationId = this.form.branchValue
						this.getOrganization(this.form.roleGenre)
						this.getJurisData(res.detail.organizations)
					} else {
						this.$message.error(res.detail.result)
					}
				})
			},
			//获取所有权限
			getPermission() {
				this.loadingCon = true
				axiosGet('/user/permissions/', {}, (res) => {
					console.log(res)
					this.loadingCon = false
					if (res.code == 0) {
						this.data = res.detail
						this.data.map((item, index) => {
							item.pid = index
						})
					} else {
						this.$message.error(res.detail.result)
					}
				})
			},
			//权限下拉值变化
			selectChange(res) {
				console.log(res)
				if (res == 20) {
					this.dataPermission = false
				} else {
					this.dataPermission = true
				}
			},
			//选择授权电梯
			choseLift() {
				localStorage.removeItem('org_type')
				let isValue = ''
				if (this.operationType == 0) {
					isValue = 11
				} else if (this.operationType == 1) {
					isValue = 12
				}
				localStorage.isUser = JSON.stringify({
					isTrue: isValue
				})
				let obj = {
					newLabel: '电梯授权',
					index: '/MainView/SystemManagement/ChoseAuthorizedElevator'
				}
				this.$store.commit('ADDTAB', obj)
				this.$router.push({
					name: 'ChoseAuthorizedElevator'
				})
			},
			//保存按钮
			addRole(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.submitLoading = true
						let checkedIds = this.$refs.treeLeft.getCheckedKeys(); // 所有被选中的节点的 key 所组成的数组数据
						let newCheckedIds = checkedIds.filter((item) => {
							return typeof item == 'string'
						})
						let organizations = []
						organizations = this.$refs.treeRight.getCheckedKeys()
						let data = {
							role_name: this.form.roleName,
							role_desc: this.form.roleComment,
							permissions: newCheckedIds,
							management: this.form.branchValue,
							management_type: this.form.dataAuthority,
							organizations: organizations,
							register_codes: this.choseLiftList,
							role_type: this.form.roleGenre,
							create_for_all:this.isChecked ? 1 : 0,
							lift: localStorage.eleLib ? (JSON.parse(localStorage.eleLib).id).toString() : '0'
						}
						let url = ''
						let method = ''
						if (this.operationType == 0) {
							url = '/user/role/'
							method = 'post'
						} else {
							url = '/user/role/' + this.compileId + '/'
							method = 'put'
						}
						axiosChange(url, method, data, (res) => {
							console.log(res)
							localStorage.removeItem('eleLib')
							localStorage.removeItem('roleMentData')
							localStorage.removeItem('choseLiftData')
							this.$store.state.choseLiftData = []
							this.submitLoading = false
							if (res.code == 0) {
								this.$message({
									type: 'success',
									message: '操作成功'
								})
								localStorage.RoleManagementFlush = JSON.stringify({
									flush: 1
								})
								this.backRouter()
							} else {
								this.$message.error(res.detail.result)
							}
						})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
	}
</script>

<style scoped lang="less">
	.listName {
		display: flex;
		justify-content: space-between;
		text-align: left;
		height: 25px;
		align-items: center;

		.listNameBox {
			height: 100%;
			display: flex;
			align-items: center;

			i {
				width: 3px;
				height: 60%;
				background: #2d8cf0;
				margin: 10px 5px;
				margin-left: 0;
			}
		}
	}

	.treeBox {
		width: 100%;
		display: flex;
		flex-direction: row;

		.treeItem {
			width: 50%;
		}
	}

	.allChose {
		text-align: left;
		padding-left: 23px;
		font-size: 14px;
	}
</style>
